package com.easycoding.framework.web.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

import com.easycoding.framework.web.WebContextHelper;

public class BaseController {
	
	protected final Log logger = LogFactory.getLog(getClass());
	
	private static final ObjectMapper OBJECTMAPPER = new ObjectMapper();
	
	public String getRequestParameter(String name) {
		return WebContextHelper.getRequest().getParameter(name);
	}
	
	public String[] getRequestParameterValues(String name){
		return WebContextHelper.getRequest().getParameterValues(name);
	}
	
	protected void ajax(HttpServletResponse response , Object data){
		JsonGenerator jsonGenerator;
		try {
			jsonGenerator = OBJECTMAPPER.getJsonFactory().createJsonGenerator(response.getWriter());
			jsonGenerator.writeObject(data);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 输出结果到页面上
	 * @param response
	 * @param content 将要输出的内容
	 * @throws IOException
	 */
	protected void printResult(Object content) throws IOException{
		HttpServletResponse response = WebContextHelper.getResponse();
		response.setContentType("application/json; charset=GBK");
		PrintWriter out = response.getWriter();
		out.print(content);
		out.flush();
		out.close();
	}
}
